package com.hyj.dev.tess4j;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;

import javax.imageio.ImageIO;

import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.testelement.AbstractScopedTestElement;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterVariables;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;

/**
 * @author hyj
 * 
 */
public class VcodeExtractor extends AbstractScopedTestElement implements PostProcessor {
	private static final long serialVersionUID = 1L;

	private MainPanel mainPanel;
	
	public VcodeExtractor() {
	}
	
//	public void setMainPanel(MainPanel mainPanel) {
//		System.out.println("设置MainPanel");
//		this.mainPanel = mainPanel;
//	}
	
	@Override
	public void process() {
		
		JMeterContext context = getThreadContext();
		
		mainPanel = MainPanel.getInstance();
		
//		SampleResult previousResult = context.getPreviousResult();
//		if (previousResult == null) {
//			return;
//		}
		
		
		JMeterVariables variables = context.getVariables();
		
		if(variables.getObject(mainPanel.getInputText()) == null) {
			String err = "【"+ getName() +"】 输入变量["+ mainPanel.getInputText() +"] 值为空或找不到";
			mainPanel.printInfo(err);
			System.out.println(err);
			throw new RuntimeException(err);
		}
		
		InputStream is = null;
		if(CaptchaType.Base64.equals(mainPanel.getCaptchaType())) {
			// 获取base字符串
			String imageCodeBase64 = variables.get(mainPanel.getInputText());
			if(imageCodeBase64.contains(",")) {
				imageCodeBase64 = imageCodeBase64.split(",")[1];
			}
			byte[] decode = Base64.getDecoder().decode(imageCodeBase64);
			is = new ByteArrayInputStream(decode);
		} else if(CaptchaType.文件流.equals(mainPanel.getCaptchaType())) {
			is = (InputStream) variables.getObject(mainPanel.getInputText());
		} else {
			throw new RuntimeException("验证码类型错误");
		}
		
		if(is == null) {
			throw new RuntimeException("没有验证码流");
		}
		
		try {
			BufferedImage image = ImageIO.read(is);
			
			ITesseract instance = new Tesseract();
			
			// 语言库位置（修改为跟自己语言库文件夹的路径）
			instance.setDatapath(mainPanel.getLanguagePath());
			// chi_sim ：简体中文， eng 根据需求选择语言库
			instance.setLanguage(mainPanel.getLanguage());
			String result = instance.doOCR(image);
			variables.put(mainPanel.getOnputText(), result.trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
